import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:permission_handler/permission_handler.dart';

class BluetoothPage extends StatefulWidget {
  const BluetoothPage({super.key});

  @override
  _BluetoothPageState createState() => _BluetoothPageState();
}

class _BluetoothPageState extends State<BluetoothPage> {
  // FlutterBluePlus flutterBlue = FlutterBluePlus.instance;
  BluetoothDevice? connectedDevice;
  List<BluetoothDevice> devicesList = [];

  @override
  void initState() {
    super.initState();
    requestPermission();
  }

  // 请求位置权限
  void requestPermission() async {
    PermissionStatus status = await Permission.location.request();
    if (status.isGranted) {
      // 权限被授予，开始扫描
      startScan();
    } else {
      // 权限被拒绝
      print('Location permission is required');
    }
  }

  // 开始扫描蓝牙设备
  void startScan() {
    FlutterBluePlus.startScan(timeout: Duration(seconds: 4));
    FlutterBluePlus.scanResults.listen((results) {
      setState(() {
        devicesList = results
            .where((result) => result.device.name.isNotEmpty)
            .map((result) => result.device)
            .toList();
      });
    });
  }

  // 连接设备
  void connectToDevice(BluetoothDevice device) async {
    await device.connect();
    setState(() {
      print('Connected to ${device.name}');
      connectedDevice = device;
    });
    discoverServices(device);
  }

  // 获取设备服务和特征
  void discoverServices(BluetoothDevice device) async {
    var services = await device.discoverServices();
    for (BluetoothService service in services) {
      for (BluetoothCharacteristic characteristic in service.characteristics) {
        // 读取特征值
        if (characteristic.properties.read) {
          var value = await characteristic.read();
          print('Read value: $value');
        }
        // 写入特征值
        if (characteristic.properties.write) {
          await characteristic.write([0x12, 0x34]);
          print('Written to characteristic');
        }
      }
    }
  }

  @override
  void dispose() {
    // 停止扫描
    FlutterBluePlus.stopScan();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    print('build length = ${devicesList.length}');
    return Scaffold(
      appBar: AppBar(
        title: Text('Bluetooth Example'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: devicesList.length,
              itemBuilder: (context, index) {
                var device = devicesList[index];
                return ListTile(
                  title: Text(device.name),
                  subtitle: Text(device.id.toString()),
                  onTap: () => connectToDevice(device),
                );
              },
            ),
          ),
          if (connectedDevice != null)
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'Connected to ${connectedDevice?.name}',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
            ),
        ],
      ),
    );
  }
}
